<script setup>
import { inject, watch, ref, nextTick } from 'vue';
import html2canvas from 'html2canvas';
import { eventBus } from '@/function/bus/index.js'

defineProps({
  msg: {
    type: String,
    required: true
  }
})
const watermarkConfig = inject('watermark')

watch(() => watermarkConfig, (newValue, oldValue) => {
  eventBus.emit('watermark', newValue)
}, {deep: true})

const loading = ref(false);

// base64转Blob
const dataURLtoBlob = function(dataurl) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
/**
 * 创建一个a链接，触发下载操作
 * @param {*} url 下载链接
 * @param {*} name 文件名
 */
const downloadFile = function(url, name) {
  const a = document.createElement("a") 
  a.setAttribute("href", url)
  a.setAttribute("download", name)
  a.setAttribute("target", "_blank")
  const clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);  
  a.dispatchEvent(clickEvent);
}

const downloadFileByBase64 = function(base64, name) {
  var myBlob = dataURLtoBlob(base64);
  var myUrl = URL.createObjectURL(myBlob); //创建图片的临时url
  downloadFile(myUrl, name)
}

const generateImages = async function() {
  loading.value = true;
  setTimeout(async () => {
    watermark.zIndex = 9;
    await nextTick(async () => {
      const element = document.getElementById('watermark')
      await html2canvas(element, {
        logging: false,
        scale: 1.5
      }).then((canvas) => {
        const page = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        page.width = canvas.width;
        page.height = canvas.height;
        page.getContext("2d").putImageData(
          ctx.getImageData(0, 0,
            canvas.width,
            canvas.height
          ), 0, 0
        );
        const base64 = page.toDataURL("image/png");
        const name = new Date().getTime();
        downloadFileByBase64(base64, name)
      })
    })
    watermark.zIndex = -1
    loading.value = false;
  }, 200)
}
</script>

<template>
  <div class="greetings" style="width: 100%;">
    <!-- <h1 class="green">{{ msg }}</h1>
    <h3>
      You’ve successfully created a project with
      <a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
      <a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
    </h3> -->
    <el-form
      class="form"
      :model="watermarkConfig"
      label-position="top"
      label-width="50px"
    >
      <el-form-item label="文字">
        <el-input v-model="watermarkConfig.content" />
      </el-form-item>
      <el-form-item label="颜色">
        <el-color-picker v-model="watermarkConfig.font.color" show-alpha />
      </el-form-item>
      <el-form-item label="字号">
        <el-slider v-model="watermarkConfig.font.fontSize" />
      </el-form-item>
      <el-form-item label="层级">
        <el-slider v-model="watermarkConfig.zIndex" />
      </el-form-item>
      <el-form-item label="旋转角度">
        <el-slider v-model="watermarkConfig.rotate" :min="-90" :max="90" />
      </el-form-item>
      <el-form-item label="间距[行，纵]">
        <el-space>
          <el-input-number v-model="watermarkConfig.gap[0]" controls-position="right" style="width: 50%;"/>
          <el-input-number v-model="watermarkConfig.gap[1]" controls-position="right" style="width: 50%;"/>
        </el-space>
      </el-form-item>
      <el-form-item label="基于容器左上角偏移[上，左]">
        <el-space>
          <el-input-number
            v-model="watermarkConfig.offset[0]"
            placeholder="offsetLeft"
            controls-position="right"
            style="width: 50%;"
          />
          <el-input-number
            v-model="watermarkConfig.offset[1]"
            placeholder="offsetTop"
            controls-position="right"
            style="width: 50%;"
          />
        </el-space>
      </el-form-item>
      <el-button color="#626aef" style="width: 100%;" @click="generateImages" :loading="loading">下载</el-button>
    </el-form>
  </div>
</template>

<style scoped>
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  position: relative;
  top: -10px;
}

h3 {
  font-size: 1.2rem;
}

.greetings h1,
.greetings h3 {
  text-align: center;
}

@media (min-width: 1024px) {
  .greetings h1,
  .greetings h3 {
    text-align: left;
  }
}
</style>
